//
//  PPFriendsManager.m
//  pickpic
//
//  Created by GaoYongyue on 16/10/3.
//  Copyright © 2016年 MicroDream. All rights reserved.
//

#import "PPFriendsManager.h"
#import "PPNetworkService.h"
#import "PPContactsModel.h"

@interface PPFriendsManager ()
@property (nonatomic, strong) NSNumber *next;
@end
@implementation PPFriendsManager

+ (instancetype)sharedInstance {
    static id instance;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        instance = self.new;
    });

    return instance;
}

- (void)fetchAllFriendsWithCallback:(CompleteCallback)callback
{
    __weak typeof(self)weakSelf = self;
    [PPNetworkService fetchFollowListWithTargetUserID:DGCurrentAccount.userID type:1 start:nil limit:50 callback:^(id data, NSError *error) {
        if (data)
        {
            if (weakSelf.next == nil) {
                [PPContactsModel performInBlock:^(NSManagedObjectContext *context) {
                    NSArray <PPContactsModel *>* localItems = [PPContactsModel where:@{@"currentUserID" : DGCurrentAccount.userID, @"relationship" : @1}];
                    [localItems enumerateObjectsUsingBlock:^(PPContactsModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        [obj delete];
                    }];
                    [context saveContext];
                }];
            }

            NSNumber *next = [[data validDictionary] validNumberForKey:@"next"];
            NSArray *users = [[data validDictionary] validArrayForKey:@"users"];
            [PPContactsModel performInBlock:^(NSManagedObjectContext *context) {
                [users enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

                    PPUserID userID = [[obj validDictionary] validStringForKey:@"user"];
                    NSNumber *relationship = [[obj validDictionary] validNumberForKey:@"relationship"];
                    PPContactsModel *contact = [PPContactsModel existingFanForUserID:userID relationShip:relationship];
                    contact.name = [[obj validDictionary] validStringForKey:@"name"];
                    contact.avatar = [[obj validDictionary] validStringForKey:@"avatar"];
                    contact.signature = [[obj validDictionary] validStringForKey:@"signature"];
                    contact.account = [obj validStringForKey:@"pickpic"];
                    contact.avatarHost = [obj validStringForKey:@"avatarHost"];
                }];
                [context saveContext];
            }];
            if ([next integerValue] != -1)
            {
                weakSelf.next = next;
                [weakSelf fetchAllFriendsWithCallback:callback];
            }
            else
            {
                weakSelf.next = nil;
            }
        }
    }];

}
@end
